<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Main Content -->
    <div class="mx-auto max-w-8xl px-4 py-6 sm:px-6 lg:px-8">
      <!-- Action Bar -->
      <div class="mb-6 flex flex-wrap items-center justify-between gap-4">
        <div class="flex items-center space-x-4">
          <el-button type="primary" class="!rounded-button whitespace-nowrap" @click="showAddDialog">
            <el-icon class="mr-2"><Plus /></el-icon>
            新增房间
          </el-button>
          <el-button class="!rounded-button whitespace-nowrap" @click="handleImport">
            <el-icon class="mr-2"><Upload /></el-icon>
            导入房间
          </el-button>
          <el-button class="!rounded-button whitespace-nowrap" @click="handleExport">
            <el-icon class="mr-2"><Download /></el-icon>
            导出房间
          </el-button>
          <el-dropdown trigger="click">
            <el-button class="!rounded-button whitespace-nowrap">
              <el-icon class="mr-2"><Operation /></el-icon>
              批量操作
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="batchDelete">批量删除</el-dropdown-item>
                <el-dropdown-item @click="batchSetStatus(1)">批量设为空闲</el-dropdown-item>
                <el-dropdown-item @click="batchSetStatus(3)">批量设为维修中</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="w-full sm:w-auto">
          <el-input
              v-model="searchQuery"
              placeholder="搜索房间号/状态"
              class="w-full sm:w-64"
              clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <!-- Room Table -->
      <div class="overflow-hidden rounded-lg bg-white shadow">
        <el-table
            v-loading="loading"
            :data="filteredRooms"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            border
            stripe
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="rid" label="id" width="70" sortable />
          <el-table-column prop="rno" label="房间号" width="100" sortable />
          <el-table-column prop="rname" label="房间照片" width="150">
            <template #default="{row}">
              <el-image
                  :src="`${SERVER_ADDR}/upload/${row.pic}`"
                  fit="cover"
                  class="w-16 h-16 rounded"
              />
            </template>
          </el-table-column>
          <el-table-column prop="rmoney" label="价格" width="100" sortable />
          <el-table-column prop="type" label="房间类型" width="150">
            <template #default="{ row }">
              <el-tag type="primary" effect="plain" v-if="row.type === 1">
                {{`单人房`}}
              </el-tag>
              <el-tag type="success" effect="plain" v-else>
                {{`双人房`}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120" sortable>
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.rstate)" effect="light">
                {{ statusMap[row.rstate] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="guest" label="入住人" width="180">
            <template #default="{ row }">
              <div v-if="row.elderlies" v-for="elderly in row.elderlies" >
                <div class="font-medium">{{ elderly.ename }}</div>
                <div class="text-xs text-gray-500">{{ elderly.phone }}</div>
              </div>
              <span v-else class="text-gray-400">暂无</span>
            </template>
          </el-table-column>
          <el-table-column prop="facilities" label="设施" min-width="200">
            <template #default="{ row }">
              <div class="flex flex-wrap gap-2">
                <el-tag
                    v-for="facility in row.goods"
                    :key="facility.id"
                    size="small"
                    type="info"
                    effect="plain"
                >
                  {{ facility.name }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button
                  size="small"
                  type="primary"
                  plain
                  class="!rounded-button whitespace-nowrap"
                  @click="editRoom(row)"
              >
                编辑
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  plain
                  class="!rounded-button whitespace-nowrap"
                  @click="confirmDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- Pagination -->
        <div class="flex items-center justify-between px-4 py-3">
          <div class="text-sm text-gray-700">
            显示 {{ (currentPage - 1) * pageSize + 1 }} 到
            {{ Math.min(currentPage * pageSize, total) }} 条，共 {{ total }} 条
          </div>
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="prev, pager, next, sizes"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
          />
        </div>
      </div>
    </div>
    <!-- Add/Edit Dialog -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑房间' : '新增房间'"
        width="600px"
        destroy-on-close
    >
      <el-form :model="roomForm" label-width="100px" :rules="rules" ref="roomFormRef">
        <el-form-item label="房间图片">
          <el-upload
              class="avatar-uploader"
              :action="`${SERVER_ADDR}/admin/file/upload`"
              name="pic"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="房间号" prop="rno">
          <el-input v-model="roomForm.rno" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="房间价格">
          <el-input-number v-model="roomForm.rmoney" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="房间类型" prop="type">
          <el-select v-model="roomForm.type" placeholder="请选择房间类型" class="w-full">
            <el-option
                v-for="type in Object.keys(typeMap)"
                :key="type"
                :label="typeMap[type]"
                :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间状态" prop="rstate">
          <el-select v-model="roomForm.rstate" placeholder="请选择房间状态" class="w-full">
            <el-option
                v-for="status in Object.keys(statusMap)"
                :key="status"
                :label="statusMap[status]"
                :value="status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间朝向">
          <el-radio-group v-model="roomForm.width">
            <el-radio-button label="东向" value="1" />
            <el-radio-button label="南向" value="2" />
            <el-radio-button label="北向" value="3" />
            <el-radio-button label="西向" value="4" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房间层高">
          <el-radio-group v-model="roomForm.height">
            <el-radio-button label="1层" value="1" />
            <el-radio-button label="2层" value="2" />
            <el-radio-button label="3层" value="3" />
            <el-radio-button label="4层" value="4" />
            <el-radio-button label="5层" value="5" />
            <el-radio-button label="6层" value="6" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房间设施" prop="facilities">
          <el-checkbox-group v-model="roomForm.goodsIds" class="flex flex-wrap gap-4">
            <el-checkbox
                v-for="facility in allFacilities"
                :key="facility.id"
                :label="facility.name"
                :value="facility.id"
            />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="房间详情">
          <el-input
              :v-model="roomForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitForm">确认</el-button>
</span>
      </template>
    </el-dialog>
    <!-- Import Dialog -->
    <el-dialog v-model="importDialogVisible" title="导入房间" width="500px">
      <div class="space-y-4">
        <div>
          <el-button type="primary" plain @click="downloadTemplate">
            <el-icon class="mr-2"><Download /></el-icon>
            下载导入模板
          </el-button>
        </div>
        <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip text-xs text-gray-500">
              仅支持 Excel 文件，文件大小不超过 5MB
            </div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmImport">开始导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="js" setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Upload,
  Download,
  Operation,
  Search,
  Delete,
  Edit,
} from '@element-plus/icons-vue';
import roomAPi from "@/api/admin/roomApi.js";
import {useTokenStore} from "@/stores/token.js";
import goodsApi from "@/api/admin/goodsApi.js";
import roomApi from "@/api/admin/roomApi.js";

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const tokenStore = useTokenStore();
//上传图片
const headers = computed(() => {
  let token = tokenStore.tokenStr;
  return {
    token
  }
})
// 状态映射
const statusMap = {
  '1': '空闲',
  '2': '已入住',
  '3': '维修中',
};
// 类型映射
const typeMap = {
  '1': '单人床',
  '2': '双人床'
};
// 所有设施选项
const allFacilities = ref([]);
// 表格数据
const rooms = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const searchQuery = ref('');
const selectedRooms = ref([]);
const dialogVisible = ref(false);
const isEditMode = ref(false);
const importDialogVisible = ref(false);
const roomFormRef = ref();
const uploadFile = ref(null);
// 房间表单
const roomForm = ref({
  rid: '',
  rno: '',
  rmoney: '',
  rstate: '1',
  type: '1',
  pic: '',
  height: '1',
  width: '1',
  goodsIds: [],
  description: '',
});
// 表单验证规则
const rules = {
  rno: [
    { required: true, message: '请输入房间号', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9-]+$/, message: '房间号只能包含字母、数字和横线', trigger: 'blur' },
  ],
  type: [{ required: true, message: '请选择房间类型', trigger: 'change' }],
  rstate: [{ required: true, message: '请选择房间状态', trigger: 'change' }],
};
// 获取所有的房间设施
const getAllFacilities = () => {
  goodsApi.selectByPage(1, 1000, {type: 1})
      .then(resp => {
        allFacilities.value = resp.data.data;
      })
};
// 获取房间类型标签样式
const getRoomTypeTagType = (type) => {
  switch (type) {
    case 1:
      return 'primary';
    case 2:
      return 'success';
    default:
      return '';
  }
};
// 获取状态标签样式
const getStatusTagType = (status) => {
  switch (status) {
    case 1:
      return 'success';
    case 2:
      return 'primary';
    case 3:
      return 'warning';
    default:
      return '';
  }
};
// 过滤后的房间数据
const filteredRooms = computed(() => {
  if (rooms.value === null){
    return [];
  }
  let filtered = rooms.value;
  return filtered
});
// 获取房间数据
const getPage = () => {
  let room = {};
  loading.value = true;
  // 房间API请求
  roomAPi.selectByPage(currentPage.value, pageSize.value, room)
      .then(resp => {
        rooms.value = resp.data.data;
        total.value = resp.data.total;
        loading.value = false;
      })
};

// 显示新增对话框
const showAddDialog = () => {
  isEditMode.value = false;
  dialogVisible.value = true;
};
// 编辑房间
const editRoom = (room) => {
  isEditMode.value = true;
  roomApi.selectById(room.rid)
      .then(resp => {
        if (resp.code == 10000) {
          roomForm.value = resp.data;
          roomForm.value.type = String(resp.data.type);
          roomForm.value.rstate = String(resp.data.rstate);
          roomForm.value.width = String(resp.data.width);
          roomForm.value.height = String(resp.data.height);
          // 将数据转为数组
          let goodsList = [];
          resp.data.goods.forEach(goods => {
            goodsList.push(Number(goods.id))
          })
          roomForm.value.goodsIds = goodsList;
          console.log(roomForm.value.goodsIds)
          imageUrl.value = `${SERVER_ADDR.value}/upload/${resp.data.pic}`;
        }
      })
  dialogVisible.value = true;
};
// 提交表单
const submitForm = () => {
  //判断是否是新建还是删除
  if (isEditMode.value){
    roomApi.update(roomForm.value)
        .then(resp => {
          if (resp.code == 10000) {
            ElMessage.success(resp.msg)
            dialogVisible.value = false
            // 重置表单
            roomForm.value ={
              rid: '',
              rno: '',
              rmoney: '',
              rstate: '1',
              type: '1',
              pic: '',
              height: '1',
              width: '1',
              goodsIds: [],
              description: '',
            };
            getPage()
          }else{
            ElMessage.error(resp.msg)
          }
        })
  }else{
    roomApi.insert(roomForm.value)
        .then(resp => {
          if (resp.code == 10000) {
            ElMessage.success(resp.msg)
            dialogVisible.value = false
            // 重置表单
            roomForm.value ={
              rid: '',
              rno: '',
              rmoney: '',
              rstate: '1',
              type: '1',
              pic: '',
              height: '1',
              width: '1',
              goodsIds: [],
              description: '',
            };
            getPage()
          }else{
            ElMessage.error(resp.msg)
          }
        })
  }

};
// 确认删除
const confirmDelete = (room) => {
  ElMessageBox.confirm(`确定要删除房间 ${room.roomNumber} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        rooms.value = rooms.value.filter((r) => r.id !== room.id);
        total.value = rooms.value.length;
        ElMessage.success('删除成功');
      })
      .catch(() => {});
};
// 批量选择
const handleSelectionChange = (selection) => {
  selectedRooms.value = [];
  selection.forEach((room) => {
    selectedRooms.value.push(room.rid)
  });
};
// 批量删除
const batchDelete = () => {
  if (selectedRooms.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRooms.value.length} 个房间吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        const ids = selectedRooms.value;
        debugger
        roomAPi.deleteByIds(ids)
            .then(resp => {
              ElMessage.success(`成功删除 ${ids.length} 个房间`);
              selectedRooms.value = [];
              getPage();
            })
      })
      .catch(() => {});
};
// 批量设置状态
const batchSetStatus = (status) => {
  if (selectedRooms.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  const ids = selectedRooms.value;
  let rooms = [];
  ids.forEach((id) => {
    rooms.push({
      rid: id,
      rstate: status,
    });
  })
  console.log(rooms)
  roomApi.updateByRooms(rooms)
      .then(resp => {
        if (resp.code === 10000) {
          selectedRooms.value = [];
          getPage();
          ElMessage.success(`成功更新 ${ids.length} 个房间状态`);
        }else {
          ElMessage.error(resp.msg);
        }

      })

};
// 导入房间
const handleImport = () => {
  importDialogVisible.value = true;
};
// 下载模板
const downloadTemplate = () => {
  ElMessage.info('模板下载功能将在实际项目中实现');
};
// 文件变化
const handleFileChange = (file) => {
  uploadFile.value = file;
};
// 确认导入
const confirmImport = () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先选择文件');
    return;
  }
// 模拟导入
  ElMessageBox.confirm('确定要导入选中的文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        loading.value = true;
        setTimeout(() => {
          const newRooms = generateRoomData().slice(0, 10);
          rooms.value = [...newRooms, ...rooms.value];
          total.value = rooms.value.length;
          importDialogVisible.value = false;
          uploadFile.value = null;
          loading.value = false;
          ElMessage.success(`成功导入 ${newRooms.length} 条房间数据`);
        }, 1500);
      })
      .catch(() => {});
};
// 导出房间
const handleExport = () => {
  if (rooms.value.length === 0) {
    ElMessage.warning('没有数据可导出');
    return;
  }
  ElMessage.info('导出功能将在实际项目中实现');
};
// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getPage();
};

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getPage();
};
const imageUrl = ref("");
// 图片上传处理
const handleImageSuccess = (response, file) => {
  if (response.code === 10000) {
    ElMessage.success('上传成功');
    imageUrl.value = `${SERVER_ADDR.value}/upload/${response.data}`;
    roomForm.value.pic = response.data;
  }

};

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 初始化
onMounted(() => {
  getPage();
  getAllFacilities();
});
</script>
<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
.upload-demo {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  background-color: #f5f7fa;
}
.upload-demo:hover {
  border-color: #409eff;
}
.el-upload__text {
  margin-top: 10px;
  color: #606266;
}
.el-upload__tip {
  margin-top: 10px;
}
</style>
